package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.*;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.service.TimeLineService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * 查询自己的时间线表中的publishId,根据这些publishId去发布表中查询发布内容
 */
@Service(version = "1.0.0")
@Slf4j
public class QuanZiApiImpl implements QuanZiApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Autowired
    private TimeLineService timeLineService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private VideoApi videoApi;

    // 评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";

    // 用户是否点赞的前缀
    private static final String COMMENT_USER_LIKE_REDIS_KEY_PREFIX = "USER_LIKE_";

    // 用户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";

    @Override
    public PageInfo<Publish> queryPublishList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        // 查询好友的动态,就是查询自己的时间线表.因为好友发动态时会把动态的ID写到自己的时间线表中来
        Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("date")));
        Query query = new Query().with(pageable);
        List<TimeLine> timeLineList = mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);
        if (CollUtil.isEmpty(timeLineList)) {
            // 没有查询到数据
            return pageInfo;
        }

        // 获取时间线列表中的发布id的列表
        List<Object> ids = CollUtil.getFieldValues(timeLineList, "publishId");

        // 根据动态ID去发布表中查询动态列表
        Query query1 = Query.query(Criteria.where("id").in(ids)).with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = mongoTemplate.find(query1, Publish.class);

        pageInfo.setRecords(publishList);
        return pageInfo;
    }


    /**
     * 发布动态
     *
     * @param publish 要保存的Publish对象
     * @return 发布成功返回动态ID
     */
    @Override
    public String savePublish(Publish publish) {
        // 对publish对象进行校验
        if (!ObjectUtil.isAllNotEmpty(publish.getText(), publish.getUserId())) {
            // 发布失败
            return null;
        }

        // 设置主键id
        publish.setId(ObjectId.get());

        try {
            // 设置自增长pid和创建时间
            publish.setPid(idService.createId(IdType.PUBLISH));
            publish.setCreated(System.currentTimeMillis());

            // 1.写入到发布表中
            mongoTemplate.save(publish);

            // 2.写入相册表
            Album album = new Album();
            album.setId(ObjectId.get());
            album.setCreated(System.currentTimeMillis());
            album.setPublishId(publish.getId());

            mongoTemplate.save(album, "quanzi_album_" + publish.getUserId());

            // 3.写入好友的时间线表(异步写入)
            timeLineService.saveTimeLine(publish.getUserId(), publish.getId());
        } catch (Exception e) {
            // 如果出现异常,需要回滚事物.因为我们使用的是MongoDB的单节点,不支持事务,所以只能手动回滚.所以这里暂时不实现此功能.
            log.error("发布动态失败～ publish = " + publish, e);
        }

        return publish.getId().toHexString();
    }


    /**
     * 查询推荐动态
     *
     * @param userId   ⽤用户id
     * @param page     当前⻚页数
     * @param pageSize 每⼀一⻚页查询的数据条数 * @return
     */
    @Override
    public PageInfo<Publish> queryRecommendPublishList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        // 查询推荐结果数据
        String key = "QUANZI_PUBLISH_RECOMMEND_" + userId;
        String data = redisTemplate.opsForValue().get(key);
        if (StrUtil.isEmpty(data)) {
            return pageInfo;
        }

        // 查询到的pid进行分⻚处理
        List<String> pids = StrUtil.split(data, ',');
        // 计算分⻚
        // [0, 10] 用HuTool
        int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
        int startIndex = startEnd[0]; //开始
        int endIndex = Math.min(startEnd[1], pids.size()); //结束

        List<Long> pidLongList = new ArrayList<>();
        for (int i = startIndex; i < endIndex; i++) {
            pidLongList.add(Long.valueOf(pids.get(i)));
        }
        if (CollUtil.isEmpty(pidLongList)) { //没有查询到数据
            return pageInfo;
        }

        // 根据pid查询publish
        Query query = Query.query(Criteria.where("pid").in(pidLongList)).with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = mongoTemplate.find(query, Publish.class);
        if (CollUtil.isEmpty(publishList)) {
            // 没有查询到数据
            return pageInfo;
        }
        pageInfo.setRecords(publishList);
        return pageInfo;
    }

    @Override
    public Publish queryPublishById(String id) {
        return mongoTemplate.findById(new ObjectId(id), Publish.class);
    }

    @Override
    public Boolean likeComment(Long userId, String publishId) {
        // 判断该用户是否已经点赞，如果已经点赞就直接返回
        if (queryUserIsLike(userId, publishId)) {
            return false;
        }

        // 保存Comment数据
        Boolean result = saveComment(userId, publishId, CommentType.LIKE, null);
        if (!result) {
            return false;
        }

        // 修改redis中的点赞数以及是否点赞

        // 修改点赞数
        String redisKey = getRedisKeyWithPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        redisTemplate.opsForHash().increment(redisKey, hashKey, 1);

        // 修改用户是否点赞
        String userHashKey = getCommentUserLikeRedisKeyWithPrefix(userId);
        redisTemplate.opsForHash().put(redisKey, userHashKey, "1");

        return true;
    }

    private String getRedisKeyWithPrefix(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX + publishId;
    }

    private String getCommentUserLikeRedisKeyWithPrefix(Long userId) {
        return COMMENT_USER_LIKE_REDIS_KEY_PREFIX + userId;
    }

    @Override
    public Boolean disLikeComment(Long userId, String publishId) {
        // 判断用户是否已经点赞，如果没有点赞就返回
        if (!queryUserIsLike(userId, publishId)) {
            return false;
        }

        // 删除评论数据
        Boolean result = removeComment(userId, publishId, CommentType.LIKE);
        if (!result) {
            return false;
        }

        // 修改Redis中的数据

        // 修改点赞数
        String redisKey = getRedisKeyWithPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        redisTemplate.opsForHash().increment(redisKey, hashKey, -1);

        // 用户是否点赞
        String userHashKey = getCommentUserLikeRedisKeyWithPrefix(userId);
        redisTemplate.opsForHash().delete(redisKey, userHashKey);

        return true;
    }

    @Override
    public Long queryLikeCount(String publishId) {
        // 从Redis中命中查询，如果命中直接返回即可
        String redisKey = getRedisKeyWithPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        Object data = redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(data)) {
            return Convert.toLong(data);
        }

        // 查询Mongodb
        Long count = queryCommentCount(publishId, CommentType.LIKE);
        // 写入Redis中
        redisTemplate.opsForHash().put(redisKey, hashKey, String.valueOf(count));

        return count;
    }

    @Override
    public Boolean queryUserIsLike(Long userId, String publishId) {
        // 从redis中查询数据
        String redisKey = getRedisKeyWithPrefix(publishId);
        String userHashKey = getCommentUserLikeRedisKeyWithPrefix(userId);
        Object data = redisTemplate.opsForHash().get(redisKey, userHashKey);
        if (ObjectUtil.isNotEmpty(data)) {
            return StrUtil.equals(Convert.toStr(data), "1");
        }

        // 查询Mongodb，确定是否已经点赞
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(userId)
                .and("commentType").is(CommentType.LIKE)
        );
        long count = mongoTemplate.count(query, Comment.class);
        if (count == 0) {
            return false;
        }

        // 写入到redis中
        redisTemplate.opsForHash().put(redisKey, userHashKey, "1");

        return true;
    }

    /**
     * 保存Comment
     *
     * @param userId      评论的人的id
     * @param publishId   动态的id
     * @param commentType 评论类型
     * @param content     评论内容
     * @return 保存评论成功:true,失败:false
     */
    private Boolean saveComment(Long userId, String publishId,
                                CommentType commentType, String content) {
        try {
            Comment comment = new Comment();

            comment.setId(ObjectId.get());// 主键id
            comment.setCommentType(commentType.getType());// 评论类型
            comment.setCreated(System.currentTimeMillis());// 创建时间
            comment.setPublishId(new ObjectId(publishId));// 这条评论所在的动态在发布表中的pid
            comment.setUserId(userId);// 评论人的id
            comment.setContent(content);// 内容

            // 查询这条动态的发布对象信息
            Publish publish = queryPublishById(publishId);
            if (ObjectUtil.isNotEmpty(publish)) {
                comment.setPublishUserId(publish.getUserId());// 这条评论所在的动态的发布人的id
            } else {
                Comment commentedComments = queryCommentById(publishId);// 也许是对评论的评论
                if (ObjectUtil.isNotEmpty(commentedComments)) {
                    comment.setPublishUserId(commentedComments.getUserId());// 这条评论所在的评论在发布表中的pid
                } else {
                    // 查询小视频
                    Video video = videoApi.queryVideoById(publishId);
                    if (ObjectUtil.isNotEmpty(video)) {
                        comment.setPublishUserId(video.getUserId());
                    } else {
                        // 其他情况,返回false
                        return false;
                    }
                }
            }

            mongoTemplate.save(comment);

            return true;
        } catch (Exception e) {
            log.error("保存Comment出错~ userId = " + userId + ", publishId = " + publishId + ", commentType = " + commentType, e);
        }
        return false;
    }

    /**
     * 删除评论数据
     *
     * @param userId 写 要删除的这条评论 的用户的id
     * @param publishId 这条评论所属的动态的publishId
     * @param commentType 评论类型(枚举)
     * @return 删除成功:true,删除失败:false
     */
    private Boolean removeComment(Long userId, String publishId, CommentType commentType) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(publishId))
                .and("commentType").is(commentType.getType()));
        return mongoTemplate.remove(query, Comment.class).getDeletedCount() > 0;
    }

    /**
     * 查询评论数量
     *
     * @param publishId 要查询评论数量的动态的publishId
     * @param commentType 评论类型(枚举)
     * @return 评论数量
     */
    private Long queryCommentCount(String publishId, CommentType commentType) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(commentType.getType()));
        return mongoTemplate.count(query, Comment.class);
    }

    @Override
    public Boolean loveComment(Long userId, String publishId) {
        // 查询该用户是否已经喜欢
        if (queryUserIsLove(userId, publishId)) {
            return false;
        }

        // 喜欢
        boolean result = saveComment(userId, publishId, CommentType.LOVE, null);
        if (!result) {
            return false;
        }

        // 喜欢成功后，修改Redis中的总的喜欢数
        String redisKey = getRedisKeyWithPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        redisTemplate.opsForHash().increment(redisKey, hashKey, 1);

        // 标记用户已经喜欢
        hashKey = getCommentUserLoveRedisKey(userId);
        redisTemplate.opsForHash().put(redisKey, hashKey, "1");

        return true;
    }

    private String getCommentUserLoveRedisKey(Long userId) {
        return COMMENT_USER_LOVE_REDIS_KEY_PREFIX + userId;
    }

    @Override
    public Boolean disLoveComment(Long userId, String publishId) {
        if (!queryUserIsLove(userId, publishId)) {
            // 如果用户没有喜欢，就直接返回
            return false;
        }

        boolean result = removeComment(userId, publishId, CommentType.LOVE);
        if (!result) {
            // 删除失败
            return false;
        }

        // 删除redis中的记录
        String redisKey = getRedisKeyWithPrefix(publishId);
        String hashKey = getCommentUserLoveRedisKey(userId);
        redisTemplate.opsForHash().delete(redisKey, hashKey);
        redisTemplate.opsForHash().increment(redisKey, CommentType.LOVE.toString(), -1);

        return true;
    }

    @Override
    public Long queryLoveCount(String publishId) {
        // 首先从redis中命中，如果命中的话就返回，没有命中就查询Mongodb
        String redisKey = getRedisKeyWithPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        Object value = redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(value)) {
            return Convert.toLong(value);
        }

        // 查询count
        Long count = queryCommentCount(publishId, CommentType.LOVE);

        // 存储到redis中
        redisTemplate.opsForHash().put(redisKey, hashKey, String.valueOf(count));

        return count;
    }

    @Override
    public Boolean queryUserIsLove(Long userId, String publishId) {
        String redisKey = getRedisKeyWithPrefix(publishId);
        String hashKey = getCommentUserLoveRedisKey(userId);
        Object value = redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(value)) {
            return StrUtil.equals(Convert.toStr(value), "1");
        }

        // 查询mongodb
        Query query = Query.query(Criteria.where("publishId")
                .is(new ObjectId(publishId))
                .and("userId").is(userId)
                .and("commentType").is(CommentType.LOVE.getType()));
        long count = mongoTemplate.count(query, Comment.class);
        if (count == 0) {
            return false;
        }

        // 标记用户已经喜欢
        redisTemplate.opsForHash().put(redisKey, hashKey, "1");

        return true;
    }

    /**
     * 查询评论列表
     *
     * @param publishId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Comment> queryCommentList(String publishId, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.asc("created")));

        Query query = new Query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(CommentType.COMMENT.getType())).with(pageRequest);

        // 查询评论列表
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);

        PageInfo<Comment> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(commentList);
        return pageInfo;
    }

    /**
     * 发表评论
     *
     * @param userId
     * @param publishId
     * @param content
     * @return
     */
    @Override
    public Boolean saveComment(Long userId, String publishId, String content) {
        return saveComment(userId, publishId, CommentType.COMMENT, content);
    }

    /**
     * 根据id查询Comment对象
     *
     * @param id
     * @return
     */
    private Comment queryCommentById(String id) {
        return mongoTemplate.findById(new ObjectId(id), Comment.class);
    }

    /**
     * 查询评论数量
     *
     * @param publishId
     * @return
     */
    @Override
    public Long queryCommentCount(String publishId) {
        return queryCommentCount(publishId, CommentType.COMMENT);
    }

    /**
     * 查询点赞消息列表
     *
     * @param userId   被查询的id
     * @param page     页码
     * @param pageSize 页大小
     * @return PageInfo<Comment>
     */
    @Override
    public PageInfo<Comment> queryLikeCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return queryCommentListByUser(userId, CommentType.LIKE, page, pageSize);
    }

    /**
     * 查询喜欢消息列表
     *
     * @param userId   被查询的id
     * @param page     页码
     * @param pageSize 页大小
     * @return PageInfo<Comment>
     */
    @Override
    public PageInfo<Comment> queryLoveCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return queryCommentListByUser(userId, CommentType.LOVE, page, pageSize);
    }

    /**
     * 查询评论消息列表
     *
     * @param userId   被查询的id
     * @param page     页码
     * @param pageSize 页大小
     * @return PageInfo<Comment>
     */
    @Override
    public PageInfo<Comment> queryCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return queryCommentListByUser(userId, CommentType.COMMENT, page, pageSize);
    }

    private PageInfo<Comment> queryCommentListByUser(Long userId, CommentType commentType, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        Query query = new Query(Criteria.where("publishUserId").is(userId)
                .and("commentType").is(commentType.getType())).with(pageRequest);
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);
        PageInfo<Comment> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(commentList);
        return pageInfo;
    }

    /**
     * 查询相册表
     *
     * @param userId   要查询的用户的id
     * @param page     页码
     * @param pageSize 页大小
     * @return PageInfo<Publish>
     */
    @Override
    public PageInfo<Publish> queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        // 查询所查用户的相册表
        Query query = new Query().with(PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created"))));
        List<Album> albumList = mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);
        if (CollUtil.isEmpty(albumList)) {
            return pageInfo;
        }

        // 取得该用户的publishId集合
        List<Object> publishIdList = CollUtil.getFieldValues(albumList, "publishId");

        // 根据publishIdList去发布表查询发布信息集合
        Query query1 = new Query(Criteria.where("id").in(publishIdList)).with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = mongoTemplate.find(query1, Publish.class);

        pageInfo.setRecords(publishList);

        return pageInfo;
    }
}